package com.bs.bsacexj.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bs.bsacexj.domain.EventEntity;
import com.bs.bsacexj.service.IEventCallBackService;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class EventCallBackService implements IEventCallBackService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 海康刷脸事件回调接口
     *
     * @param param 消息体
     * @return 响应结果
     */
    @Override
    public boolean personFaceCallback(Object eventParam) {
        try {
            try {
                List<EventEntity>  list=new ArrayList<>();
                JSONObject eventObj = JSONObject.parseObject(JSONObject.toJSONString(eventParam))  ;
                JSONObject params = JSONObject.parseObject(eventObj.getString("params"));
                JSONArray events = params.getJSONArray("events");
                for(Object item : events) {

                    JSONObject event = (JSONObject) item;
                    JSONObject data = event.getJSONObject("data");
                    EventEntity entity = new EventEntity();

                    entity.setOrgId(event.getString("7939"));


                    entity.setEventId(event.getString("eventId"));
                    entity.setEventType(event.getInteger("eventType"));
                    entity.setHappenTime(event.getString("happenTime"));
                    entity.setDoorIndexCode(event.getString("srcIndex"));
                    entity.setDoorName(event.getString("srcName"));
                    entity.setDoorName(event.getString("srcParentIndex"));
                    entity.setSrcType(event.getString("srcType"));

                    entity.setCardNo(data.getString("ExtEventCardNo"));
                    entity.setInAndOutType(data.getInteger("ExtEventInOut"));
                    entity.setEventName(data.getString("ExtEventName"));
                    entity.setPersonName(data.getString("ExtEventPersonName"));
                    entity.setPersonId(data.getString("ExtEventPersonNo"));
                    entity.setPicUri(data.getString("ExtEventPictureURL"));
                    entity.setSvrIndexCode(data.getString("svrIndexCode"));

                    //entity.setDoorRegionIndexCode(event.getString("doorRegionIndexCode"));
                    //entity.setEventTime(data.getString("ExtReceiveTime"));
                    //entity.setIdentityCardUri(event.getString("identityCardUri"));
                    //entity.setOrgIndexCode(event.getString("orgIndexCode"));
                    //entity.setOrgName(event.getString("orgName"));

                    entity.setSendTime(params.getString("sendTime"));
                    list.add(entity);
                }
                return saveEvent(list);
            } catch (Exception ex) {
                logger.error("海康刷卡回调失败{},消息体：{}", ex, eventParam);
                return false;
            }
        } catch (Exception ex) {
            logger.error("海康刷脸回调失败{},消息体：{}", ex, eventParam);
            return false;
        }
    }

    /**
     * 海康刷卡事件回调接口
     *
     * @param param 消息体
     * @return 响应结果
     */

    @Override
    public boolean personCardCallback(Object eventParam) {
        try {
            List<EventEntity>  list=new ArrayList<>();
            JSONObject eventObj = (JSONObject) eventParam;
            JSONObject params = JSONObject.parseObject(eventObj.getString("params"));
            JSONArray events = params.getJSONArray("events");
            for(Object item : events) {

                JSONObject event = (JSONObject) item;
                JSONObject data = event.getJSONObject("data");
                EventEntity entity = new EventEntity();

                entity.setOrgId(event.getString("7939"));


                entity.setEventId(event.getString("eventId"));
                entity.setEventType(event.getInteger("eventType"));
                entity.setHappenTime(event.getString("happenTime"));
                entity.setDoorIndexCode(event.getString("srcIndex"));
                entity.setDoorName(event.getString("srcName"));
                entity.setDoorName(event.getString("srcParentIndex"));
                entity.setSrcType(event.getString("srcType"));

                entity.setCardNo(data.getString("ExtEventCardNo"));
                entity.setInAndOutType(data.getInteger("ExtEventInOut"));
                entity.setEventName(data.getString("ExtEventName"));
                entity.setPersonName(data.getString("ExtEventPersonName"));
                entity.setPersonId(data.getString("ExtEventPersonNo"));
                entity.setPicUri(data.getString("ExtEventPictureURL"));
                entity.setSvrIndexCode(data.getString("svrIndexCode"));

                //entity.setDoorRegionIndexCode(event.getString("doorRegionIndexCode"));
                //entity.setEventTime(data.getString("ExtReceiveTime"));
                //entity.setIdentityCardUri(event.getString("identityCardUri"));
                //entity.setOrgIndexCode(event.getString("orgIndexCode"));
                //entity.setOrgName(event.getString("orgName"));

                entity.setSendTime(params.getString("sendTime"));
                list.add(entity);
            }
            return saveEvent(list);
        } catch (Exception ex) {
            logger.error("海康刷卡回调失败{},消息体：{}", ex, eventParam);
            return false;
        }
    }

    /**
     * 海康刷指纹事件回调接口
     *
     * @param param 消息体
     * @return 响应结果
     */
    @Override
    public boolean personFingerCardCallback(Object param) {
        try {

            return true;
        } catch (Exception ex) {
            logger.error("海康刷指纹回调失败{},消息体：{}", ex, param);
            return false;
        }
    }

    private boolean saveEvent(List<EventEntity> eventList) {
        // 保存事件
        OkHttpClient client = new OkHttpClient();
        String url = "http://aqdlbz-sit.bosafe.com/prod-api/business/accessControlApi/doorEvents";
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, JSON.toJSONString(eventList));
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try (
                Response response = client.newCall(request).execute()) {
            ResponseBody body = response.body();
            logger.info("双控门事件回调结果："+JSONObject.toJSONString(body));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
